package image

import (
	"encoding/json"
	"fmt"
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/image"
	imageReq "github.com/flipped-aurora/gin-vue-admin/server/model/image/request"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type HarborService struct{}

// GetImageList 分页获取gameZone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (harborService *HarborService) GetImageList(info imageReq.ImageSearch, page int, size int) (list []image.Image, err error) {
	url := fmt.Sprintf("%s/api/v2.0/projects/shaoge/repositories?page=%d&page_size=%d", global.GVA_CONFIG.Harbor.Addr, page, size)
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	// 添加必要的认证头，例如使用基本认证
	req.SetBasicAuth(global.GVA_CONFIG.Harbor.UserName, global.GVA_CONFIG.Harbor.Password)
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}

	//https://www.jb51.net/jiaoben/312741njx.htm
	// 初始化一个Person结构体的切片来存储解码后的数据
	var datas []image.HarborSearch

	// 解码JSON数据到结构体切片
	err1 := json.Unmarshal(body, &datas)
	if err != nil {
		log.Fatal(err1)
		return
	}

	images := []image.Image{}

	// 打印解码后的数据
	for _, item := range datas {
		t, _ := time.ParseInLocation("2006-01-02 15:04:05", item.UpdateTime, time.Local)
		images = append(images, image.Image{Name: item.Name, UpdatedAt: t})
	}

	return images, err
}
